package com.fhx.core.utils

import android.app.Activity
import android.content.Context
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

/**
 * Created by Administrator on 2017/8/30.
 */
object WonderfulKeyboardUtils {
    fun editKeyboard(
        event: MotionEvent,
        view: View?,
        activity: Activity
    ) {
        try {
            if (view != null && view is EditText) {
                val location = intArrayOf(0, 0)
                view.getLocationInWindow(location)
                val left = location[0]
                val top = location[1]
                val right = (left
                        + view.getWidth())
                val bottom = top + view.getHeight()
                if (event.rawX < left || event.rawX > right || event.y < top || event.rawY > bottom
                ) {
                    val token = view.getWindowToken()
                    val inputMethodManager = activity
                        .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    inputMethodManager.hideSoftInputFromWindow(
                        token,
                        InputMethodManager.HIDE_NOT_ALWAYS
                    )
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun hideSoftInput(activity: Activity) {
        val imm =
            activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(activity.currentFocus!!.windowToken, 0)
    }

    fun showSoftInput(activity: Activity) {
        val imm =
            activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm != null) {
            activity.currentFocus!!.requestFocus()
            imm.showSoftInput(activity.currentFocus, 0)
        }
    }
}